package com.xl.basic.entity;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xl.basic.utils.JacksonUtils;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.experimental.Accessors;

import java.util.ArrayList;
import java.util.List;

/**
 * 包装常见的报错类型和分页，列表，数据类型的返回result
 */
@Getter
@AllArgsConstructor
@Accessors(chain = true)
public enum ResultEnums {
    Success(10000, "成功"),
    Exception(-14444, "系统异常"),

    BusinessError(-10000, "业务异常"),
    ParamError(-10001, "参数异常"),

    LoginError(-11000, "用户未登录"),
    AuthError(-11001, "没有操作权限"),
    ;

    private final Integer code;
    private final String message;

    public <T> Result<T> getResult() {
        return getResult(this.message);
    }

    public <T> Result<T> getResult(String message) {
        return new Result<>(this.code, message);
    }

    public <T> Result<T> getDataResult(T data) {
        return new Result<>(this.code, this.message, data);
    }

    public <T> Result<List<T>> getListResult(List<T> list) {
        return new Result<>(this.code, this.message, list);
    }

    public <T> Result<List<T>> getPageResult(List<T> list, Long total) {
        return new Result<>(this.code, this.message, list, total);
    }

    public <T> Result<List<T>> getPageResult(Page<T> page) {
        if (page == null) {
            return getPageResult(new ArrayList<>(), 0L);
        }

        List<T> list = page.getRecords() != null ? page.getRecords() : new ArrayList<>();
        return getPageResult(list, page.getTotal());
    }

    public <S, T> Result<List<T>> getPageResult(Page<S> page, Class<T> ignoredT) {
        if (page == null) {
            return getPageResult(null);
        }

        if (page.getRecords() == null) {
            return getPageResult(new Page<T>().setTotal(page.getTotal()));
        }

        try {
            ObjectMapper objectMapper = JacksonUtils.objectMapper();
            List<T> list = objectMapper.readValue(objectMapper.writeValueAsString(page.getRecords()),
                    new TypeReference<>() {
                    }
            );

            return getPageResult(list, page.getTotal());
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }
}
